package com.pobing.seuic;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import com.seuic.scankey.IKeyEventCallback;
import com.seuic.scankey.ScanKeyService;
import com.seuic.scanner.DecodeInfo;
import com.seuic.scanner.DecodeInfoCallBack;
import com.seuic.scanner.Scanner;
import com.seuic.scanner.ScannerFactory;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;

/**
 * Seuic 东集手持设备插件
 */
public class SeuicScannerPlugin extends CordovaPlugin implements DecodeInfoCallBack {

    // 插件回传
    private CallbackContext receiveScanCallback = null;
    Scanner scanner;
    private ScanKeyService mScanKeyService = ScanKeyService.getInstance();
    final static String TAG = "SeuicScannerPlugin";
    private Activity context;

    /**
     * 插件初始化
     * @param cordova
     * @param webView
     */
    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova,webView);
        Log.v(TAG, "initialize");
        context = cordova.getActivity();
    }

    /**
     * 插件访问接口
     * @param action          The action to execute.
     * @param args            The exec() arguments.
     * @param callbackContext The callback context used when calling back into JavaScript.
     * @return
     * @throws JSONException
     */
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        Log.v(TAG, "============== execute ===========: " + action);

        if (action.equals("requestScan")) {
            Log.v(TAG, "requestScan");
            // 连接一下
            receiveScanCallback = callbackContext;
            mScanKeyService.registerCallback(mCallback, "250");
            receiveScanCallback = callbackContext;
            return true;
        }

        if (action.equals("setScanParams")) {

        }

        Log.v(TAG, "============== done   ===========: " + action);
        return false;
    }

    @Override
    public void onDecodeComplete(final DecodeInfo decodeInfo) {
        Log.v(TAG, "onDecodeComplete");
        Message msg=new Message();
        msg.what=1;
        msg.obj=decodeInfo.barcode;
        handler.sendMessage(msg);
    }

    /*按键按下抬起执行扫描和 停止扫码的功能*/
    private IKeyEventCallback mCallback = new IKeyEventCallback.Stub() {
        @Override
        public void onKeyDown(int keyCode) throws RemoteException {
            scanner.startScan();
        }
        @Override
        public void onKeyUp(int keyCode) throws RemoteException {
            scanner.stopScan();
        }
    };

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String result = msg.obj.toString();
                    Log.v(TAG, "扫描结果： result = " + result);
                    ArrayList<PluginResult> arguments = new ArrayList<PluginResult>();
                    arguments.add(new PluginResult(PluginResult.Status.OK, result));
                    PluginResult progressResult = new PluginResult(PluginResult.Status.OK, arguments);
                    progressResult.setKeepCallback(true);
                    receiveScanCallback.sendPluginResult(progressResult);
                    break;
                default:
                    break;
            }
        };
    };

    //监听 屏幕亮屏（息屏）状态
    boolean isScreen=true;
    private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            Log.v(TAG, "监听 屏幕亮屏（息屏）状态");
            final String action = intent.getAction();
            if(Intent.ACTION_SCREEN_ON.equals(action)){
                Log.i("aaa","亮屏");
                scanner = ScannerFactory.getScanner(SeuicScannerPlugin.this.context);
                scanner.open();
                scanner.setDecodeInfoCallBack(SeuicScannerPlugin.this);
                mScanKeyService.registerCallback(mCallback, "250");
                isScreen=true;

            }else if(Intent.ACTION_SCREEN_OFF.equals(action)) {
                isScreen = false;
                Log.i("aaa","息屏");
                mScanKeyService.unregisterCallback(mCallback);
                if (scanner != null) {
                    scanner.close();
                    scanner.setDecodeInfoCallBack(null);
                    scanner=null;
                }
            }
        }
    };
}
